﻿using UnityEngine;
using System.Collections;
using DG.Tweening;
using System;
using System.Collections.Generic;
/// <summary>
/// 扫码功能
/// </summary>
public class ScanCodeController : MonoSingleton<ScanCodeController>
{
    SmTransferCtrl transCtrl;
    ScannerCtrl scannerCtrl;
    //角色位置 
    //Vector3 rolePos = new Vector3(-5.72f, 0f, -0.38f);
    //商品    
    List<Transform> goods;
    [SerializeField]
    List<float> movePointsList = new List<float>() { };
    Transform goodsPoint;
    //小票
    Transform ticket;
    Vector3 orgTicketPos;
    //放置初始化位置
    float orgPosX = -0.242f;//0.758f;

    float moveSpeed = 12f;

    RuntimeAnimatorController con;

    GameObject effect_redRay;
    GameObject effect_redCode;
    protected override void Awake()
    {
        //TODO 转动传输带 人物移动  购买商品移动
        transCtrl = transform.Find("304050301_cuasongdai").GetComponent<SmTransferCtrl>();
        
        moveSpeed = transCtrl.speed * moveSpeed;
        //扫码器
        scannerCtrl = transform.Find("304050302").GetComponent<ScannerCtrl>();

        goodsPoint = transform.Find("goods");

        ticket = transform.Find("ticket");
        orgTicketPos = ticket.localPosition;

        effect_redRay = scannerCtrl.transform.Find("502004085").gameObject;
        effect_redCode = transform.Find("502004085_1").gameObject;
        //设置人物
        //SuperMarketGame.Instance.SetRolePosition(rolePos);

        //mjbTest
        //InitTest();
    }

    public void EnableRayEffect(bool enable)
    {
        effect_redRay.SetActive(enable);
    }
    public void PlayCodeEffect()
    {
        effect_redCode.SetActive(true);
        //-5.266 0.701  0.925  266.643  -39.82001   220.842
        StartCoroutine(TimeUtility.DelayInvoke(0.3f, () =>
        {
            effect_redCode.SetActive(false);
        }));        
    }

    private float interval = 8f;
    public float totalCount = 0;
    private void Update()
    {
        totalCount += Time.deltaTime;
        if (totalCount >= interval)
        {
            if (scannerCtrl.codeTransforms != null && scannerCtrl.codeTransforms.Count > 0)
            {
                Transform trans = scannerCtrl.codeTransforms.Peek();
                Animator animator = trans.parent.gameObject.GetComponent<Animator>();
                if (animator == null)
                {
                    animator = trans.parent.gameObject.AddComponent<Animator>();
                    animator.runtimeAnimatorController = con;
                    animator.Rebind();
                }
                animator.CrossFade("shake", 0.2f);
                MarketMainSceneCtrl.Instance.PlayBuyAreaHandTween(new Vector3(-5.824f, 1.25f, 1.514f), new Vector3(0.004f, 0.004f, 0.004f));
                StartCoroutine(TimeUtility.DelayInvoke(3f, () =>
                {
                    MarketMainSceneCtrl.Instance.handClick.gameObject.SetActive(false);
                    MarketMainSceneCtrl.Instance.handClick.DOKill();
                }));
                totalCount = 0f;
            }
        }
    }
    /// <summary>
    /// 测试用例
    /// </summary>
    void InitTest()
    {
        Transform goods1 = goodsPoint.GetChild(0);
        Transform goods2 = goodsPoint.GetChild(1);
        Transform goods3 = goodsPoint.GetChild(2);
        Transform goods4 = goodsPoint.GetChild(3);
        Transform goods5 = goodsPoint.GetChild(4);
        Transform goods6 = goodsPoint.GetChild(5);
        List<Transform> temp = new List<Transform>();
        temp.Add(goods1); temp.Add(goods2); temp.Add(goods3);
        temp.Add(goods4); temp.Add(goods5); temp.Add(goods6);
        Init(temp);

    }
    public void Init(List<Transform> _goods)
    {
        transCtrl.isMove = true;
        //打开计价器 UI
        ScanPriceController.Instance.OpenView();
        ScanPriceController.Instance.ViewSet(true);

        con = ResourceManager.Instance.GetResource("super_market/super_market_controller/fruit_zhendong", typeof(RuntimeAnimatorController), enResourceType.Prefab, false, false).m_content as RuntimeAnimatorController;

        goods = new List<Transform>();
        goods = _goods;

        //初始化条形码       
        //for (int i = goods.Count-1; i >= 0; i--)
        for (int i = 0; i < goods.Count; i++)
        {
            goods[i].SetParent(goodsPoint);
            goods[i].localPosition = new Vector3((goods.Count-1-i) * 0.5f + orgPosX, 0.14f, 0);
            goods[i].localRotation = Quaternion.Euler(new Vector3(goods[i].localEulerAngles.x, 0, 0));
            goods[i].localScale = new Vector3(goods[i].localScale.x, goods[i].localScale.y, Mathf.Abs(goods[i].localScale.z));

            GameObject code =  GameObject.Instantiate(CommonUtility.LoadPrefab(SuperMarketResPath.BarCodeObject));
            code.transform.name = code.transform.name + i;
            code.transform.SetParent(goods[i]);
            code.transform.localPosition = new Vector3(0,0,0.01f);
            code.transform.localScale = new Vector3(1.5f, 1.5f, 1.5f);
            //添加扫码物品
            scannerCtrl.AddBarCode(code.transform);
        }
        if (transCtrl.isMove)
        {            
            GoodsMoving(goods.ToArray(), -1.583f, moveSpeed, () =>
            {
                Debug.Log(" IsScan===  ");
                transCtrl.isMove = false;
                scannerCtrl.SetColliderEnable(true);
                scannerCtrl.IsScan = true;
            }); 
        }
    }

    public void GoodsMoving(Transform[] trans, float target, float speed, Action act = null)
    {
        // start  0.242  end -2.077    =  res -2.156   2 1 0
        transCtrl.isMove = true;
        int index = 0;
        //for (int i = 0; i < trans.Length; i++)
        for (int i = trans.Length - 1;  i >= 0; i--)
        {
            //Debug.Log(i + " ,trans[i] ==  "+ trans[i].name);   
            trans[i].DOLocalMoveX(-1.583f + (trans.Length - i - 1) * 0.5f, speed).SetEase(Ease.Linear).OnComplete(() => {
                index++;
                if (index == trans.Length)
                {
                    transCtrl.isMove = false;
                    if (act != null)
                        act();
                }
            });
        }         
    }
    /// <summary>
    /// 扫码完成物品堆放
    /// </summary>
    /// <param name="tarTrans">目标物</param>
    /// <param name="index">摆放的索引值</param>
    /// <param name="act"></param>
    public void ScanFallDown(Transform tarTrans ,int index ,Action act)
    {
        transCtrl.isMove = true;
        for (int i = 0; i < goods.Count; i++)
        {
            if (goods[i] == tarTrans.parent)
            {
                //Debug.Log("ScanFallDown === "+index);
                //goods.Count
                Vector3 point = new Vector3(-2.1512f, 0.1f, -0.31f + (0.62f / (goods.Count-1))* index);//(index-1) * 0.31f
                goods[i].DOLocalMove(point, 1f).SetEase(Ease.Linear).OnComplete(()=> {
                    transCtrl.isMove = false;
                    if (act != null)
                        act();
                });
                break;
            }
        }
    }
    
    /// <summary>
    /// 出账单
    /// </summary>
    public void Billing()
    {
        //隐藏商品
        int index = 0;
        foreach (var item in goods)
        {
            index++;
            Destroy(item.gameObject);
            //放回购物车
            //SuperMarketGame.Instance.PutGoodsBackShopCar(item, index);
        }
        //0.827
        AudioManager.Instance.PlaySound(SuperMarketResPath.Sound_604050104,true,true);
        ticket.DOLocalMoveY(0.827f, 2f).OnComplete(() =>
        {
            AudioManager.Instance.StopSound(AudioManager.Instance.GetAudioClip(SuperMarketResPath.Sound_604050104));
            //TODO  购物单自动飞入角色手中 完成整个购物  -5.5  0.244 -0.357
            ticket.DOLocalJump(new Vector3(-5.5f, 0.244f, -0.357f), 0.3f, 1, 1.8f).OnComplete(()=> {
                //TODO  画面转场主场景
                //付款结束，游戏完成。配合界面彩带撒花特效。 603010707
                //MarketMainSceneCtrl.Instance.PlaySuccessEffect(true, RoleInSuperMarketCtrl.Instance.transform.position);
                //SuperMarketGame.Instance.soundCtrl.PlaySoundAnim(SuperMarketResPath.Sound_603010707, () => {
                //MarketMainSceneCtrl.Instance.PlaySuccessEffect(false, RoleInSuperMarketCtrl.Instance.transform.position);
                SuperMarketGame.Instance.soundCtrl.PlaySoud(SuperMarketResPath.Sound_603010707);
                StartCoroutine(TimeUtility.DelayInvoke(3f, () =>
                {
                    AudioManager.Instance.StopSound(AudioManager.Instance.GetAudioClip(SuperMarketResPath.Sound_603010707));
                    SuperMarketGame.Instance.OnEndGame();
                    OnReset();
                }));
                //});
                //SuperMarketGame.Instance.OnEndGame();
                //OnReset();
            });
        });
    }

    /// <summary>
    /// 传输带是否运行
    /// </summary>
    /// <returns></returns>
    public bool GetTransIsMove()
    {
        return transCtrl.isMove;
    }

    /// <summary>
    /// 重置游戏
    /// </summary>
    public void OnReset()
    {
        //TODO
        totalCount = 0f;
        ticket.localPosition = orgTicketPos;
        goods = null;
        gameObject.SetActive(false);
        scannerCtrl.TotalPrice = 0;
        ScanPriceController.Instance.ViewSet(false);
    }
}
